import {
  openPort, calculation
} from '@/api/login'
import * as earthMath from '@/utils/MathUtil'
import bus from '@/utils/eventBus'
export default {
  data() {
    return {
      center: {
        lng: 116.404,
        lat: 39.915,
        h: 0
      },
      zoom: 12,
      // 无人机信息（新的）
      wuRenJiData: {
        lat: 0,
        lon: 0,
        hgt: 0
      },
      // 无人机信息（旧的）
      wrjData: {
        appId: '',
        data: {
          mountInfo: [],
          openid: '暂未连接无人机',
          uavInfo: {
            airSpeed: 0,
            altitude: 0,
            armd: 0,
            barometerTemp: 0,
            battaryRemain: 0.0,
            climbRate: 0.0,
            current: 0,
            currentMountType: [],
            customData: {
              controlStatus: 0,
              isEnable: 0,
              joystickConnectionStatus: 0,
              maxHeight: 0.0,
              positionStatus: 0,
              returnAltitude: 0.0,
              returnSpeed: 0.0,
              returnVoltage: 0.0,
              signalStatus: 0,
              transportStatus: 0
            },
            dateTime: '',
            distanceToHome: 0,
            distanceToNext: 0,
            flightDistance: 0,
            flightMode: '',
            flightSortie: '',
            flightState: 0,
            flightTime: '0.00',
            groundSpeed: 0.0,
            height: 0.0,
            imuTemp: 0,
            isLocation: '0',
            latitude: 38.045474,
            longitude: 114.502461,
            pitch: 0.0,
            platformType: 0,
            push_status: '0',
            roll: 0.0,
            satCount: 0,
            taskId: '',
            uid: 0,
            unmannedId: 0,
            voltage: 0.0,
            yaw: 0.0
          },
          videoInfo: [
            {
              vUrl: '',
              videoType: 'RTMP'
            }
          ]
        },
        deviceHardId: '',
        deviceType: '0',
        systemCode: 'MMC'
      },
      // 航向信息
      wrjHangXiang: {
        heading: 0,
        length: 0,
        pitch: 0,
        posType: '暂无',
        solnSVs: 0,
        fxjl: 0,
        fxxj: 0,
        fxfyj: 0,
        fxphjd: 0
      },
      // 最佳位置信息
      wrjWeiZhi: {
        diffAge: 0,
        hgt: 0,
        lat: 0.0,
        lon: 0.0
      },
      // 水平仪最佳位置信息
      spyWeiZhi: {
        hgt: 0,
        lat: 0.0,
        lon: 0.0
      },
      BMap: null,
      map: null,
      options: {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      },
      // 航向数据
      hxsjList: [],
      json_fields: {
        时间: 'nowData',
        航向角: 'heading',
        '基线长(m)': 'length'
      },
      header: '航向数据表',
      NowDateName: `${this.getNowDate()}航向数据信息.xls`,
      xieJu: 0, // 斜距,
      xJAdd: 0, // 斜距累计A++
      isSave: false, // 保存状态
      saveTimes: 0, // 保存时长
      drawCount: 0, // 上图计数
      calculationCount: 0, // 计算计数
      xieJuDataList: [], // 保存斜距数据List
      xj_json_fields: {
        // 保存斜距数据表头
        时间: 'nowData',
        斜距: 'xj'
      },
      headerxj: '数据表',
      // Excel名称
      downLoadXieJuExcelName: `斜距表数据信息${this.getNowDate(1)}.xls`
    }
  },

  created() {
    // localStorage.setItem('lon', '0')
    // localStorage.setItem('lat', '0')
    // localStorage.setItem('hgt', '0')
    // localStorage.setItem('longitude', '0')
    // localStorage.setItem('latitude', '0')
    // localStorage.setItem('height', '0')
    // 注册回调函数
    this.$socket.registerCallBack(this.testData)
    // 打开串口
    // openPort().then(res => {
    //   if (res.code === 0) {
    //     // 注册回调函数
    //     this.$socket.registerCallBack(this.testData)
    //   }
    // })
  },
  destroyed() {
    // 取消回调函数
    this.$socket.unRegisterCallBack(this.testData)
  },
  mounted() {
    this.calHorizontalDistance()
  },
  methods: {
    /**
     * 保存斜距值A++
     */
    saveXieJuNumAdd() {
      this.xJAdd++
      this.xieJuDataList.push({ nowData: this.getNowDate(), xj: this.xieJu })
      bus.$emit('tabWrjXjToAddTabTwo', this.xieJu)
    },
    /**
     * 保存斜距数据到Excel，并且将数据添加到校准计算data中
     */
    saveXieJuDataToExcel() {
      this.xJAdd = 0
      this.xieJuDataList = []
    },
    calHorizontalDistance() {
      // 无人机位置
      // let lat1 = this.wrjData.data.uavInfo.latitude // 无人机纬度
      // let lng1 = this.wrjData.data.uavInfo.longitude // 无人机经度
      // let height1 = this.wrjData.data.uavInfo.height // 无人机高度
      let lat1 = this.wuRenJiData.lat // 无人机纬度
      let lng1 = this.wuRenJiData.lon // 无人机经度
      let height1 = this.wuRenJiData.hgt // 无人机高度
      if (isNaN(lat1) || isNaN(lng1)) {
        return
      }
      // 航向位置
      let lat2 = this.wrjWeiZhi.lat
      let lng2 = this.wrjWeiZhi.lon
      let height2 = this.wrjWeiZhi.hgt
      if (isNaN(lat2) || isNaN(lng2)) {
        this.wrjWeiZhi.lat = 0
        this.wrjWeiZhi.lon = 0
        return
      }

      // 高度差
      if (isNaN(height1)) {
        height1 = parseFloat(height1)
      } else {
        height1 = 0
      }
      if (isNaN(height2)) {
        height2 = parseFloat(height2)
      } else {
        height2 = 0
      }
      let heg = Math.abs(height1 - height2)

      this.wrjHangXiang.fxjl = earthMath
        .calHorizontalDistance(lat1, lng1, lat2, lng2)
        .toFixed(4)
      this.wrjHangXiang.fxxj = earthMath
        .calObliqueDistance(lat1, lng1, lat2, lng2, heg)
        .toFixed(4)
      this.wrjHangXiang.fxfyj = earthMath
        .calObliqueAngle(lat1, lng1, lat2, lng2, heg)
        .toFixed(4)
      this.wrjHangXiang.fxphjd = earthMath
        .calBevelAngle(lat1, lng1, lat2, lng2)
        .toFixed(4)
    },
    handler({ BMap, map }) {
      this.BMap = BMap
      this.map = map
      this.setPosition()
    },
    // 客户端向服务端发送数据
    socketFsBtn() {
      this.$socket.send('AAA客户端发送的数据')
    },
    // 接收到数据 data
    testData(receiveSocketData) {
      let data = JSON.parse(receiveSocketData.data)
      if (
        data.msgType === 'INFO' ||
        data.msgType === 'HANG_XIANG' ||
        data.msgType === 'ZUI_JIA_WEI_ZHI' ||
        data.msgType === 'SHUI_PING_YI_ZUI_JIA_WEI_ZHI' ||
        data.msgType === 'WU_REN_JI_BI_HE_TONG_LU'
      ) {
        console.log(data.msgType, data.msg)
        // 判断是否为无人机航向socket消息
        if (data.msgType === 'HANG_XIANG') {
          this.wrjHangXiang = JSON.parse(data.msg)
        }
        // 判断是否为无人机最佳位置socket消息
        if (data.msgType === 'ZUI_JIA_WEI_ZHI') {
          this.wrjWeiZhi = JSON.parse(data.msg)
        }
        // 判断是否为水平仪最佳位置socket消息
        if (data.msgType === 'SHUI_PING_YI_ZUI_JIA_WEI_ZHI') {
          this.spyWeiZhi = JSON.parse(data.msg)
          // 水平仪经纬高
          this.$store.commit('editSpyLon', this.spyWeiZhi.lon)
          this.$store.commit('editSpyLat', this.spyWeiZhi.lat)
          this.$store.commit('editSpyHgt', this.spyWeiZhi.hgt)
        }
        // 判断是否为无人机socket消息
        if (data.msgType === 'WU_REN_JI_BI_HE_TONG_LU') {
          this.wuRenJiData = JSON.parse(data.msg)
          this.$store.commit('editWrjLon', this.wuRenJiData.lon)
          this.$store.commit('editWrjLat', this.wuRenJiData.lat)
          this.$store.commit('editHeight', this.wuRenJiData.hgt)
          // 取到无人机位置数据后上图
          this.center.lng = this.wuRenJiData.lon
          this.center.lat = this.wuRenJiData.lat
          if (this.center.lng && this.center.lat) {
            // 每收到一次消息绘画计数叠加一次
            this.drawCount++
            // 每隔50次则上图一次
            if (this.drawCount >= 5) {
              this.setPosition()
              this.drawCount = 0
            }
          }
        }
        this.calHorizontalDistance()
        this.$forceUpdate()
        // 每收到一次计算计数叠加一次
        this.calculationCount++
        // 每隔100次则计算斜距一次
        if (this.calculationCount >= 5) {
          // 获取斜距
          this.getXieJu()
          this.calculationCount = 0
        }
      }
    },
    /**
     *获取斜距
     */
    getXieJu() {
      let xjParams = {
        lon1: this.$store.state.wrjLon,
        lat1: this.$store.state.wrjLat,
        hgt1: this.$store.state.wrjHgt,
        lon2: this.$store.state.spyLon,
        lat2: this.$store.state.spyLat,
        hgt2: this.$store.state.spyHgt
      }
      if (!xjParams.lon1 || !xjParams.lat1 || !xjParams.hgt1 || !xjParams.lon2 || !xjParams.lat2 || !xjParams.hgt2) {
        return
      }
      calculation(xjParams, false).then(res => {
        // //console.log(res, 'xiejucanshu---- res')
        this.xieJu = res.data
      })
    },
    // 地图定位标注
    setPosition() {
      let BMap = this.BMap
      let map = this.map
      let point = new BMap.Point(this.center.lng, this.center.lat)
      let marker = new BMap.Marker(point) // 创建标注
      map.addOverlay(marker) // 将标注添加到地图中
      map.panTo(point)
    },
    // /**
    //  * 保存
    //  */
    // hxsjBcClick() {
    //   this.hxsjList.push({
    //     nowData: this.getNowDate(),
    //     heading: this.wrjHangXiang.heading,
    //     length: this.wrjHangXiang.length
    //   })
    // },
    // /**
    //  * 结束
    //  */
    // hxsjJsClick() {
    //   this.hxsjList = []
    // },
    /**
     * 开始保存
     */
    saveStart() {
      this.isSave = true
      this.saveTimes = 0
      // 点击开始保存按钮清空数据
      this.hxsjList = []
      // 计时秒
      this.timer = setInterval(() => {
        this.saveTimes += 1
        this.saveTimes = Number(this.saveTimes.toFixed(2))
        this.hxsjList.push({
          nowData: this.getNowDate(),
          heading: this.wrjHangXiang.heading,
          length: this.wrjHangXiang.length
        })
      }, 1000)
    },
    /**
     * 停止保存
     */
    saveStop() {
      // 停止
      this.isSave = false
      clearInterval(this.timer)
      this.saveTimes = 0
    },
    /**
     * 时间
     */
    getNowDate() {
      var date = new Date()
      var sign2 = ':'
      var year = date.getFullYear() // 年
      var month = date.getMonth() + 1 // 月
      var day = date.getDate() // 日
      var hour = date.getHours() // 时
      var minutes = date.getMinutes() // 分
      var seconds = date.getSeconds() // 秒
      var weekArr = [
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六',
        '星期天'
      ]
      var week = weekArr[date.getDay()]
      // 给一位数的数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (day >= 0 && day <= 9) {
        day = '0' + day
      }
      if (hour >= 0 && hour <= 9) {
        hour = '0' + hour
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = '0' + minutes
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = '0' + seconds
      }
      return hour + sign2 + minutes + sign2 + seconds
    }
  }
}
